package com.fable.common.utils;

import com.fable.common.enums.BusiErrCode;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class JsonResult implements Serializable {

    private static final long serialVersionUID = 1L;
    private static final String CODE = "code";
    private static final String SUCCESS = "success";
    private static final Integer SUCCESS_CODE = 1;
    private static final Integer FAIL_CODE = 0;
    private static final String DATA = "data";
    private static final String REDIRECT_URL = "redirectURL";
    private static final String CSRF_TOKEN = "csrf_token";

    private Map<String, Object> map = new ConcurrentHashMap<String, Object>();

    public static JsonResult getInstance() {
        return new JsonResult();
    }

    public JsonResult() {
        map.put(SUCCESS, true);
        map.put(CODE,SUCCESS_CODE);
    }

    public void setErrCode(BusiErrCode errCode) {
        map.put(SUCCESS, FAIL_CODE);
        if (errCode != null) {
            map.put(CODE, errCode.code());
            map.put(ConvertErrorCodeUtil.ERROR_MESSAGE, StringUtils.isBlank(ConvertErrorCodeUtil.getErrorMessage(errCode.code())) ? errCode.msg() : ConvertErrorCodeUtil.getErrorMessage(errCode.code()));
        }
    }

    public void setCustomErrCode(String code, String msg) {
        map.put(SUCCESS, FAIL_CODE);
        map.put(CODE, code);
        map.put(ConvertErrorCodeUtil.ERROR_MESSAGE, msg);
    }

    public void success() {
        map.put(SUCCESS, SUCCESS_CODE);
    }

    public void setErrMsg(String errMsg) {
        map.put(CODE,0);
        map.put(ConvertErrorCodeUtil.ERROR_MESSAGE, errMsg);
    }

    public void setData(Object data) {
        map.put(DATA, data);
    }

    public void setKey(String key, Object data) {
        map.put(key, data);
    }

    public void setRedirectUrl(String redirectUrl) {
        map.put(REDIRECT_URL, redirectUrl);
    }

    public void setCsrfToken(String csrfToken) {
        map.put(CSRF_TOKEN, csrfToken);
    }

    public Map<String, Object> getMap() {
        return map;
    }

}
